package com.baidu.sggc.third.ab.agent;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.List;

@Component
@Slf4j
public class AbAppInstanceApi {

  @Value("${third.ab.appInstanceListApi}")
  private String appInstanceListApi;

  @Autowired
  private RestTemplate restTemplate;

  @Value(value = "${third.ab.Authorization}")
  private String apiKey;

  public List<AppInstanceListRespDto.AppInstance> queryAppInstanceList(AppInstanceListReqDto reqDto) {
    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(appInstanceListApi)
            .queryParam("page", reqDto.getPage())
            .queryParam("limit", reqDto.getLimit());

    String url = builder.toUriString();

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", apiKey);
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("aibase-project-id", "1234"); // 添加项目ID
    HttpEntity<?> entity = new HttpEntity<>(headers);

    ResponseEntity<AppInstanceListRespDto> response = restTemplate.exchange(
            url,
            HttpMethod.GET,
            entity,
            AppInstanceListRespDto.class
    );

    if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
      AppInstanceListRespDto body = response.getBody();
      if (body.getCode() == 0) {
        return body.getResult().getData();
      } else {
        throw new RuntimeException("接口返回失败: " + body.getMessage());
      }
    } else {
      throw new RuntimeException("HTTP请求失败，状态码: " + response.getStatusCode());
    }
  }

}
